/*
 * @Author: laladuduqq
 * @Date: 2024-12-17 14:27:48
 * @LastEditors: laladuduqq
 * @LastEditTime: 2024-12-17 14:34:09
 */
#include "RGB.h"
#include "drivers/dev_pwm.h"
#include "rtdef.h"
#include "rttypes.h"

#define LOG_TAG              "RGB"
#define LOG_LVL              LOG_LVL_DBG
#include <ulog.h>

#define PWM_DEV_NAME        "pwm5"  /* PWM设备名称 */
#define RGB_B_CHANNEL         1   /* PWM通道 */
#define RGB_G_CHANNEL         2   /* PWM通道 */
#define RGB_R_CHANNEL        3   /* PWM通道 */

struct rt_device_pwm *pwm_dev;      /* PWM设备句柄 */

/**
 * @description: RGB pwm 设备初始化
 * @return {*}
 * @author: laladuduqq
 */
int rgb_device_init(void)
{
    rt_err_t ret = RT_EOK;

    /* 查找设备 */
    pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    if (pwm_dev == RT_NULL)
    {
        LOG_E("pwm sample run failed! can't find %s device!\n", PWM_DEV_NAME);
        ret = -RT_ERROR;
    }
    
    rt_pwm_enable(pwm_dev, RGB_B_CHANNEL);
    rt_pwm_enable(pwm_dev, RGB_G_CHANNEL);
    rt_pwm_enable(pwm_dev, RGB_R_CHANNEL);
    return ret;
}

INIT_ENV_EXPORT(rgb_device_init); //rtt 自动初始化PWM设备

/**
  * @brief          显示RGB
  * @param      aRGB:0xaaRRGGBB,'aa' 是透明度,'RR'是红色,'GG'是绿色,'BB'是蓝色
  * @retval         none
  */

void aRGB_led_show(uint32_t aRGB)
{
    static uint8_t alpha;
    static uint16_t red,green,blue;

    alpha = (aRGB & 0xFF000000) >> 24;
    red = ((aRGB & 0x00FF0000) >> 16) * alpha;
    green = ((aRGB & 0x0000FF00) >> 8) * alpha;
    blue = ((aRGB & 0x000000FF) >> 0) * alpha;


    /* 设置PWM周期和脉冲宽度默认值 */
    rt_pwm_set(pwm_dev, RGB_B_CHANNEL, 65535, blue);
    rt_pwm_set(pwm_dev,RGB_G_CHANNEL,65535,green);
    rt_pwm_set(pwm_dev,RGB_R_CHANNEL,65535,red);
}

